package com.asset.service.impl;

import com.asset.mapper.DepaMapper;
import com.asset.pojo.Department;
import com.asset.service.DepartmentService;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 11725
 */
@Slf4j
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DepaMapper depaMapper;

    @Override
    public PageResult<Department> selectByPage(Integer page, Integer rows, Boolean selectAll) {
        if (selectAll == null) {
            // 分页
            PageHelper.startPage(page, rows);
        }
        // 查询
        List<Department> depaList = depaMapper.selectAll();
        // 结果校验
        if (CollectionUtils.isEmpty(depaList)) {
            throw new RuntimeException("无匹配的查询结果");
        }

        PageInfo<Department> info = new PageInfo<>(depaList);

        return new PageResult<>(info.getTotal(), depaList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(Department department) {
        // 参数处理
        department.setId(null);
        // 新增
        depaMapper.insert(department);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    synchronized public void update(Department department) {
        Department record = new Department();
        record.setId(department.getId());
        record.setName(department.getName());
        int row = depaMapper.updateByPrimaryKeySelective(record);
        if (row != 1) {
            throw new AssetManageException(AssetExceptionEnum.DEPARTMENT_INFO_UPDATE_FAIL);
        }
    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public Department selectById(Long id) {
        return depaMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Department> selectByIds(List<Long> ids) {
        return depaMapper.selectByIdList(ids);
    }
}
